#' GIRF with randomly entering a regime
#'
GIRFTwoRegime <- function(regdata,endovar,countryrlt,p = p, q=1, nF = 12, delta = 0.01,impvar = NULL, impcnt = 'USA', k = 1){
  # impcnt: 脉冲发动的国家
  # impvar: 脉冲发动的变量
  # delta： 脉冲的大小
  # q: 外生变量的滞后期数
  source('./GVAR_UsingR2e/InitialData.R')
  # 往前预测nF期
  benchvar_bench <- NULL
  benchvar_imp <- NULL
  newdata_bench <- list()
  newdata_imp <- list()
  for (n in 1:nF) {
    # print(n)
    # browser()
    newFVdata_bench <- NULL
    newFVdata_imp <- NULL
    for (country in unique(regdata$ID)) {
      # print(country)
      # 不确定性在美国是内生变量
      if (country %in% 'USA'){
        endovar_tmp <- c(endovar, 'unctn')
        exogvar_tmp <- paste(country, endovar,'_FL0',sep = '')
      }else {
        endovar_tmp <- endovar
        exogvar_tmp <- paste(country, endovar,'_FL0',sep = '') %>% c('unctn')
      }
      # browser()
      # 逐步向前预测、更新数据
      if ('rawrlt' %in% names(countryrlt[[country]])){
        if (n == 1){
          newdata_bench[[country]] <- newdata_imp[[country]] <-
            dplyr::select(countryrlt[[country]][['rawrlt']]$varresult[[1]]$model, -y) %>%
            .[nrow(countryrlt[[country]][['rawrlt']]$varresult[[1]]$model),]
          if ((!is.null(impvar)) & (country %in% impcnt)){
            newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'rawrlt',
                                       endovar_tmp,delta = delta,impvar = impvar, k = k)
            newpred_imp  <-  newpred_med[['newpred_imp']]
            newpred_bench <- newpred_med[['newpred_bench']]
          } else {
            newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'rawrlt',endovar_tmp)
            newpred_bench  <- newpred_med[['newpred_bench']]
            newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                       regime = 'rawrlt',endovar_tmp, eps = newpred_med[['eps']]) %>%
              .[['newpred_imp']]
          }
        }else {
          newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'rawrlt',endovar_tmp)
          newpred_bench  <- newpred_med[['newpred_bench']]
          newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                     regime = 'rawrlt',endovar_tmp, eps = newpred_med[['eps']]) %>%
            .[['newpred_imp']]
        }
      }else {
        # 进入非线性体制，并找到最后一期的阈值变量数值
        # ifelse (impvar %in% 'TFP',
        #         a <- regdata$gdp[regdata$ID %in% country],
        #         a <- regdata$gdp[regdata$ID %in% country] %>% diff())
        # a <- pat
        a <- regdata$gdp[regdata$ID %in% country] %>% diff()
        a <- a[length(a)]
        if (a <= countryrlt[[country]]$thr){
          if (n == 1){
            newdata_bench[[country]] <- newdata_imp[[country]] <-
              dplyr::select(countryrlt[[country]][['dn']]$varresult[[1]]$model, -y) %>%
              .[nrow(countryrlt[[country]][['dn']]$varresult[[1]]$model),]
            if ((!is.null(impvar)) & (country %in% impcnt)){
              newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'dn',
                                         endovar_tmp,delta = delta,impvar = impvar, k = k)
              newpred_imp  <-  newpred_med[['newpred_imp']]
              newpred_bench <- newpred_med[['newpred_bench']]
            } else {
              newpred_med <- InitialData(countryrlt,country,newdata_bench,
                                         regime = 'dn',endovar_tmp)
              newpred_bench  <- newpred_med[['newpred_bench']]
              newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                         regime = 'dn',endovar_tmp, eps = newpred_med[['eps']]) %>%
                .[['newpred_imp']]
            }
          }else {
            newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'dn',endovar_tmp)
            newpred_bench  <- newpred_med[['newpred_bench']]
            newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                       regime = 'dn',endovar_tmp, eps = newpred_med[['eps']]) %>%
              .[['newpred_imp']]
          }
        }else if (a > countryrlt[[country]]$thr){
          # 初始化
          if (n == 1){
            newdata_bench[[country]] <- newdata_imp[[country]] <-
              dplyr::select(countryrlt[[country]][['up']]$varresult[[1]]$model, -y) %>%
              .[nrow(countryrlt[[country]][['up']]$varresult[[1]]$model),]
            if ((!is.null(impvar)) & (country %in% impcnt)){
              newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'up',
                                         endovar_tmp,delta = delta,impvar = impvar, k = k)
              newpred_imp  <-  newpred_med[['newpred_imp']]
              newpred_bench <- newpred_med[['newpred_bench']]
            } else {
              newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'up',endovar_tmp)
              newpred_bench  <- newpred_med[['newpred_bench']]
              newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                         regime = 'up',endovar_tmp, eps = newpred_med[['eps']]) %>%
                .[['newpred_imp']]
            }
          }else {
            newpred_med <- InitialData(countryrlt,country,newdata_bench,regime = 'up',endovar_tmp)
            newpred_bench  <- newpred_med[['newpred_bench']]
            newpred_imp <- InitialData(countryrlt,country,newdata_imp,
                                       regime = 'up',endovar_tmp, eps = newpred_med[['eps']]) %>%
              .[['newpred_imp']]
          }
        }
      }

      if (any(is.na(newpred_imp[,'cpi']))) browser()

      # 储存每次更新的内生变量
      if (country %in% 'USA'){
        benchvar_bench <- data.frame(cnt = country, n = n) %>% cbind(newpred_bench) %>% rbind(benchvar_bench,.)
        benchvar_imp <- data.frame(cnt = country, n = n) %>% cbind(newpred_imp) %>% rbind(benchvar_imp,.)
      }else {
        benchvar_bench <- data.frame(cnt = country, n = n) %>%
          cbind(newpred_bench, data.frame(unctn = NA)) %>% rbind(benchvar_bench,.)
        benchvar_imp <- data.frame(cnt = country, n = n) %>%
          cbind(newpred_imp, data.frame(unctn = NA)) %>% rbind(benchvar_imp,.)
      }

      # browser()
      # 为下一步预测更新newdata：内生变量
      for (j in p:1) {
        if (j == 1){
          newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% paste(endovar_tmp, '.l',as.character(j), sep = ''))] <-
            newpred_bench
          newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% paste(endovar_tmp, '.l',as.character(j), sep = ''))] <-
            newpred_imp
        }else {
          newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% paste(endovar_tmp, '.l',as.character(j), sep = ''))] <-
            newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% paste(endovar_tmp, '.l',as.character(j - 1), sep = ''))]
          newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% paste(endovar_tmp, '.l',as.character(j), sep = ''))] <-
            newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% paste(endovar_tmp, '.l',as.character(j - 1), sep = ''))]
        }
      }
      # 为下一步预测更新newdata：外生变量:1...更新第一期至最后一期
      for (i in 1:q) {
        if (i == 1){
          newdata_bench[[country]][,(names(newdata_bench[[country]]) %in%
                                       (paste(exogvar_tmp,'1',sep = '') %>% str_remove('0')))] <-
            newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% exogvar_tmp)]
          newdata_imp[[country]][,(names(newdata_imp[[country]]) %in%
                                     (paste(exogvar_tmp,'1',sep = '') %>% str_remove('0')))] <-
            newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% exogvar_tmp)]
        } else {
          newdata_bench[[country]][,(names(newdata_bench[[country]]) %in%
                                       (paste(exogvar_tmp,as.character(i),sep = '') %>% str_remove('0')))] <-
            newdata_bench[[country]][,(names(newdata_bench[[country]]) %in%
                                         (paste(exogvar_tmp,as.character(i-1),sep = '') %>% str_remove('0')))]
          newdata_imp[[country]][,(names(newdata_imp[[country]]) %in%
                                     (paste(exogvar_tmp,as.character(i),sep = '') %>% str_remove('0')))] <-
            newdata_imp[[country]][,(names(newdata_imp[[country]]) %in%
                                       (paste(exogvar_tmp,as.character(i-1),sep = '') %>% str_remove('0')))]
        }
      }

      # 准备各国内生变量数据，用来更新外国变量
      if (country %in% 'USA'){
        newFVdata_bench <- cbind(data.frame(ID = country, Time = '2017/12/31'),dplyr::select(newpred_bench, -unctn)) %>%
          rbind(newFVdata_bench,.)
        newFVdata_imp <- cbind(data.frame(ID = country, Time = '2017/12/31'),dplyr::select(newpred_imp, -unctn)) %>%
          rbind(newFVdata_imp,.)
      }else {
        newFVdata_bench <- cbind(data.frame(ID = country, Time = '2017/12/31'),newpred_bench) %>%
          rbind(newFVdata_bench,.)
        newFVdata_imp <- cbind(data.frame(ID = country, Time = '2017/12/31'),newpred_imp) %>%
          rbind(newFVdata_imp,.)
      }
    }

    # 为下一步预测更新newdata：外生变量:2...更新第0期
    FV_bench <- GVAR_Ft(newFVdata_bench,TradeWeight[['2016']])
    FV_imp <- GVAR_Ft(newFVdata_imp,TradeWeight[['2016']])
    names(FV_bench) <- newFVdata_bench$ID
    names(FV_imp) <- newFVdata_imp$ID
    for (country in unique(regdata$ID)) {
      # 不确定性在美国是内生变量
      if (country %in% 'USA'){
        endovar_tmp <- c(endovar, 'unctn')
        exogvar_tmp <- paste(country, endovar,'_FL0',sep = '')
      }else {
        endovar_tmp <- endovar
        exogvar_tmp <- paste(country, endovar,'_FL0',sep = '') %>% c('unctn')
      }

      if (country %in% 'USA'){
        newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% exogvar_tmp)] <-
          FV_bench[[country]][,(colnames(FV_bench[[country]]) %in% exogvar_tmp)]
        newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% exogvar_tmp)] <-
          FV_imp[[country]][,(colnames(FV_imp[[country]]) %in% exogvar_tmp)]
      }else {
        newdata_bench[[country]][,(names(newdata_bench[[country]]) %in% exogvar_tmp)] <-
          cbind((FV_bench[[country]][,(colnames(FV_bench[[country]]) %in% exogvar_tmp)] %>%
                   matrix(1,3) %>% as.data.frame()),
                data.frame(unctn.l1 = newdata_bench[['USA']]$unctn.l1))
        newdata_imp[[country]][,(names(newdata_imp[[country]]) %in% exogvar_tmp)] <-
          cbind((FV_imp[[country]][,(colnames(FV_imp[[country]]) %in% exogvar_tmp)] %>%
                   matrix(1,3) %>% as.data.frame()),
                data.frame(unctn.l1 = newdata_imp[['USA']]$unctn.l1))
      }
    }
  }
  # browser()
  benchvar_imp$state <- 'imp'
  benchvar_bench$state <- 'bench'
  return(list(benchvar_bench = benchvar_bench, benchvar_imp = benchvar_imp))
}
